package com.swpu.service_remind.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.swpu.service_remind.service.OssService;
import com.swpu.service_remind.util.ConstantProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upLoadFileAvatar(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantProperties.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantProperties.ACCESS_KEY_ID;
        String accessKeySecret = ConstantProperties.SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantProperties.BUCKET_NAME;

        OSS ossClient = null;
        try {
            String fileName = file.getOriginalFilename();
            //取得文件后缀
        //    fileName=file.getOriginalFilename().substring(file.getOriginalFilename().length()-4);

            String uuid = UUID.randomUUID().toString().replace("-", "");

            fileName=uuid+fileName;
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            fileName=dataPath+"/"+fileName;
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            System.out.println("文件上传成功");
            return url;
        } catch (Exception e) {
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


    }
}
